package com.doctor.ui.consulting;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;

import com.doctor.adapter.ShowImageAdapter;
import com.doctor.bean.ContactsBean;
import com.doctor.comm.ConstConfig;
import com.doctor.comm.DialogHelper;
import com.doctor.comm.FileHelper;
import com.doctor.comm.ImageHelper;
import com.doctor.comm.DialogHelper.MultipleDialogCallback;
import com.doctor.comm.DialogHelper.NoticeDialogCallback;
import com.doctor.comm.ImageHelper.TakePictureCallback;
import com.doctor.database.DbOperator;
import com.doctor.net.NetUtil;
import com.doctor.ui.BaseFragment;
import com.doctor.ui.DragImageActivity;
import com.doctor.ui.R;
import com.doctor.view.NoScrollGridView;

public class SendEmailFrag extends BaseFragment{

	/**
	 * 邮件发送
	 */
	
	private Context context;
	private EditText emailReceiver,title,content;   //标题、内容
	private EditText diagRequire,requireDoctor,contactsNum; //双诊要求、请求医师、联系电话
	private TextView addReceiverBtn,uploadBtn,takePhotoBtn;    //上传、拍照
	private LinearLayout sendBtn,cancelBtn;     //保存、取消	
	//显示图片之用
	private NoScrollGridView gridView;
	private ShowImageAdapter adapter;
	private Uri imageUri;
	private List<String> beanList;		
	private String[] receivers;
	private ReceiverCast receiverCast;
	
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		this.context=getActivity();
		
		View view=inflater.inflate(R.layout.send_email, container, false);
		initiaView(view);
		getData();
		
		//注册短信发送状态广播
		if (receiverCast==null) {
			receiverCast=new ReceiverCast();
		}
		IntentFilter filter=new IntentFilter();
		filter.addAction("SENT_SMS_ACTION");
		context.registerReceiver(receiverCast, filter);		
		
		return view;
	}
	
	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		emailReceiver.setText("");
		//取消广播
		if (receiverCast!=null) {
			try {
				context.unregisterReceiver(receiverCast);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	
	@Override
	protected void getData() {
		// TODO Auto-generated method stub
		String emailNumber=getArguments().getString("email");
		emailReceiver.setText(emailNumber+";");
	}
	
	@Override
	protected void initiaView(View view) {
		// TODO Auto-generated method stub
		title=(EditText) view.findViewById(R.id.title);
		content=(EditText) view.findViewById(R.id.content);
		diagRequire=(EditText) view.findViewById(R.id.require);
		requireDoctor=(EditText) view.findViewById(R.id.requireDoctor);
		contactsNum=(EditText) view.findViewById(R.id.contactsNum);
		
		ImageListener imageListener=new ImageListener();
		uploadBtn=(TextView) view.findViewById(R.id.uploadBtn);
		uploadBtn.setOnClickListener(imageListener);
		
		takePhotoBtn=(TextView) view.findViewById(R.id.takePhotoBtn);
		takePhotoBtn.setOnClickListener(imageListener);
		
		sendBtn=(LinearLayout) view.findViewById(R.id.sendBtn);		
		sendBtn.setOnClickListener(new OnClickListener() {		
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (!NetUtil.hasNetwork(context)) {
					Toast.makeText(context, "请连接网络！", Toast.LENGTH_SHORT).show();
					return;
				}
				String emailReceiver_txt=emailReceiver.getText().toString().trim();
				String title_txt=title.getText().toString().trim();
				ArrayList<String> images=adapter.getPics();
				String diagRequire_txt=diagRequire.getText().toString().trim();
				String requireDoctor_txt=requireDoctor.getText().toString().trim();
				String contactsNum_txt=contactsNum.getText().toString().trim();
				String content_txt=content.getText().toString().trim();
				
				if (emailReceiver_txt==null || "".equals(emailReceiver_txt)) {
					Toast.makeText(context, "请填写收件人！", Toast.LENGTH_SHORT).show();
					return;
				}
				if (title_txt==null || "".equals(title_txt)) {
					Toast.makeText(context, "请填写标题！", Toast.LENGTH_SHORT).show();
					return;
				}
				
				receivers= emailReceiver_txt.split(";");
				StringBuilder builder=new StringBuilder();
				if (diagRequire_txt!=null && !"".equals(diagRequire_txt)) {
					builder.append("双诊要求："+diagRequire_txt);
				}
				if (requireDoctor_txt!=null && !"".equals(requireDoctor_txt)) {
					builder.append("\n请求医师："+requireDoctor_txt);
				}
				if (contactsNum_txt!=null && !"".equals(content_txt)) {
					builder.append("\n联系电话："+contactsNum_txt);
				}
				if (content_txt!=null && !"".equals(content_txt)) {
					builder.append("\n内容："+content_txt);
				}
				builder.append("");
				
				
				Intent sendEmailIntent;
				if (images!=null && images.size()>0) {
					//带有附件
					sendEmailIntent=new Intent(Intent.ACTION_SEND_MULTIPLE);
					sendEmailIntent.putExtra(Intent.EXTRA_EMAIL, receivers);
					sendEmailIntent.putExtra(Intent.EXTRA_SUBJECT, title_txt);
					sendEmailIntent.putExtra(Intent.EXTRA_TEXT, builder.toString());
					sendEmailIntent.setType("text/plain");
					ArrayList<Uri> uris = new ArrayList<Uri>(images.size());
					for (String picPath : images) {
						uris.add(Uri.fromFile(new File(picPath)));
					}
					sendEmailIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris);
					startActivityForResult(Intent.createChooser(sendEmailIntent, "选择邮件客户端:"),3);
				} else {
					//普通文本邮件
					sendEmailIntent=new Intent(Intent.ACTION_SENDTO);
					sendEmailIntent.setType("text/plain");
					sendEmailIntent.setData(Uri.parse("mailto:"+receivers[0]));
					if (receivers.length>1) {
						//发送给多个人
						String[] receiversLeft=emailReceiver_txt.substring(emailReceiver_txt.indexOf(";")+1, emailReceiver_txt.length()).split(";");
						sendEmailIntent.putExtra(Intent.EXTRA_EMAIL, receiversLeft);
					}
					sendEmailIntent.putExtra(Intent.EXTRA_SUBJECT, title_txt);
					sendEmailIntent.putExtra(Intent.EXTRA_TEXT, builder.toString());
					startActivityForResult(Intent.createChooser(sendEmailIntent, "选择邮件客户端:"),4);
				}
			}
		});
		
		cancelBtn=(LinearLayout) view.findViewById(R.id.cancelBtn);
		cancelBtn.setOnClickListener(new OnClickListener() {			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				getActivity().getSupportFragmentManager().popBackStack();
			}
		});
		
		emailReceiver=(EditText) view.findViewById(R.id.smsReceiver);
		addReceiverBtn=(TextView) view.findViewById(R.id.addReceiverBtn);
		
		addReceiverBtn.setOnClickListener(new OnClickListener() {			
			@Override
			public void onClick(View v) {
				List<ContactsBean> beanList=DbOperator.getInstance(context).selectDoctorContacts(2);
				if (beanList!=null && beanList.size()>0) {
					DialogHelper.showMultipleDialog(context, null, beanList,new MultipleDialogCallback() {					
						@Override
						public void onConfirmClicked(Map<Integer, ContactsBean> map) {
							// TODO Auto-generated method stub
							if (map.size()>0) {
								StringBuilder builder=new StringBuilder();
								builder.append(emailReceiver.getText().toString());
								for (int id : map.keySet()) {
									builder.append(map.get(id).getContacts()+";");
								}
								emailReceiver.setText(builder.toString());
							}
						}
					});
				} else {
					Toast.makeText(context, "没有可供选择的联系人！", Toast.LENGTH_SHORT).show();
				}
			}
		});
		
		gridView=(NoScrollGridView) view.findViewById(R.id.gridView);
		beanList=new ArrayList<String>();
		adapter=new ShowImageAdapter(context, beanList);
		gridView.setAdapter(adapter);
		gridView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				// TODO Auto-generated method stub
				String picPath=(String) arg1.getTag(R.id.bean_tag);
				Intent intent=new Intent(getActivity(),DragImageActivity.class);
				intent.putExtra(getString(R.string.uri), picPath);
				startActivity(intent);
				
			}
		});
		gridView.setOnItemLongClickListener(new OnItemLongClickListener() {
			@Override
			public boolean onItemLongClick(AdapterView<?> arg0, final View arg1,
					int arg2, long arg3) {
				// TODO Auto-generated method stub
				
				DialogHelper.noticeDialog(context, null, new NoticeDialogCallback() {	
					@Override
					public void onClicked(int position) {
						// TODO Auto-generated method stub
						if (position==1) {
							String pic=(String) arg1.getTag(R.id.bean_tag);
							adapter.removeBean(pic);
						}
					}
				});
				return false;
			}
		});		
	}	
	
	/**
	 * 上传和拍照
	 * @author
	 *
	 */
	private class ImageListener implements OnClickListener{
		@Override
		public void onClick(View arg0) {
			// TODO Auto-generated method stub
			if (arg0==uploadBtn) {
				ImageHelper.selectPicture(SendEmailFrag.this, ConstConfig.CHOOSE_PICTURE,null);
			} else if (arg0==takePhotoBtn) {
				ImageHelper.selectPicture(SendEmailFrag.this, ConstConfig.TAKE_PICTURE,new TakePictureCallback() {					
					@Override
					public void onGetImageName(Uri imageUri) {
						// TODO Auto-generated method stub
						SendEmailFrag.this.imageUri=imageUri;
					}
				});
			}
		}
	}
	
	//选择图片或拍照完成后返回图片路径，发邮件后发提醒短信
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		
		if (requestCode==3 || requestCode==4) {
			//邮件后发送提醒短信
			if (receivers!=null && receivers.length>0) {
				List<String> mobiles=DbOperator.getInstance(context).getMobileByEmail(receivers);
				if (mobiles.size()<=0) {
					return;
				}
				SmsManager smsManager=SmsManager.getDefault();
				Intent sendIntent=new Intent("SENT_SMS_ACTION");
				PendingIntent sendPi=PendingIntent.getBroadcast(context, 0, sendIntent, 0);
				String message="技术咨询邮件已发送至您的邮箱，请查收";
				for (String mobile : mobiles) {
					smsManager.sendTextMessage(mobile, null, message, sendPi, null);
					ContentValues values=new ContentValues();
					values.put("date", System.currentTimeMillis());
					values.put("read", 0);
					values.put("type", 2);
					values.put("address", mobile);
					values.put("body", message);
					//写入短信库
					context.getContentResolver().insert(Uri.parse("content://sms/sent"), values);
				}	
			}
			return;
		}
		
		//-1=RESULT_OK
		if (resultCode==-1) {
			Uri imageUri = null;	
			switch (requestCode) {
			case ConstConfig.CHOOSE_PICTURE:
				if (data!=null) {
					imageUri=data.getData();
				}
				break;
				
			case ConstConfig.TAKE_PICTURE:
				imageUri=SendEmailFrag.this.imageUri;
				SendEmailFrag.this.imageUri=null;
				break;
				
			default:
				break;
			}
			if (imageUri!=null) {
				String pic = FileHelper.uri2Path(context, imageUri);
				if (pic != null && pic.length() > 0) {
					adapter.addBean(pic);
					adapter.notifyDataSetChanged();
				}
			}
		}		
	}	
	
	
	//用于接收短信发送之后状态的广播
	private class ReceiverCast extends BroadcastReceiver{
		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			if (getResultCode()==Activity.RESULT_OK) {
				Toast.makeText(context, "提示短信发送成功！", Toast.LENGTH_SHORT).show();
			}
		}		
	}
	
	@Override
	public void onDestroyView() {
		// TODO Auto-generated method stub
		super.onDestroyView();
		if (adapter != null) {
			adapter.clear();
		}
	}
	
}
